package com.jinbei.security;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinbei.common.annotation.EncryptMethod;
import com.jinbei.common.util.AesUtil;
import com.jinbei.filter.XssFilter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

/**
 * @author zflu
 * 加密密response json
 * 使用 aes解密
 * Created by lucky on 2018/8/23.
 */
//@ControllerAdvice
public class EncryptResponseBodyAdvice extends XssFilter implements ResponseBodyAdvice {

    private final Logger logger = LoggerFactory.getLogger(EncryptResponseBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Method method = returnType.getMethod();
        if(method.isAnnotationPresent(EncryptMethod.class)){
            EncryptMethod annotation = method.getAnnotation(EncryptMethod.class);
            boolean encrypt = annotation.isEncrypt();
            if(encrypt){
                ObjectMapper objectMapper = new ObjectMapper();
                String result = null;
                try {
                    result = objectMapper.writeValueAsString(body);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    logger.error("ResponseBody 加密失败!   error :",e);
                    return result;
                }
                if(StringUtils.isBlank(ENCRYPT_KEY.get())){
                    return AesUtil.encrypt(result);
                }else{
                    return AesUtil.encrypt(result,ENCRYPT_KEY.get(),null);
                }
            }
        }
        return body;
    }
}
